package com.ruoyi.framework.interceptor;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author dingling
 * @desc  mybatis 拦截器、在执行数据库操作之前执行
 * @date 2023-08-30 15:10
 **/

@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class MybatisInterceptor implements Interceptor {

    @Autowired
    TokenService tokenService;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];

        // sql类型：insert、update、select、delete
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];

        if (parameter == null) {
            return invocation.proceed();
        }

        // 当sql为新增或更新类型时，自动填充操作人相关信息
        if (SqlCommandType.INSERT == sqlCommandType) {
            // 获取当前登录用户信息
            SysUser sysUser = new SysUser();
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (loginUser != null){
                sysUser = loginUser.getUser();
            }

            Field[] fields = getAllFields(parameter);
            for (Field field : fields) {
                try {
                    // 注入创建人ID
                    if ("createBy".equals(field.getName())) {
                        // 登录人id
                        field.setAccessible(true);
                        field.set(parameter, sysUser.getUserName());
                        field.setAccessible(false);
                    }
                    // 注入创建人
                    if ("createdByName".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, sysUser.getUserName());
                        field.setAccessible(false);
                    }
                    //注入创建时间
                    if ("createTime".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }

                    if ("updateBy".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, sysUser.getUserName());
                        field.setAccessible(false);
                    }
                    if ("lastModifiedByName".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, sysUser.getUserName());
                        field.setAccessible(false);
                    }
                    if ("updateTime".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (SqlCommandType.UPDATE == sqlCommandType) {
            // 获取当前登录用户信息
            SysUser sysUser = new SysUser();
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (loginUser != null){
                sysUser = loginUser.getUser();
            }

            Field[] fields = getAllFields(parameter);
            for (Field field : fields) {
                try {
                    if ("updateBy".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, sysUser.getUserName());
                        field.setAccessible(false);
                    }
                    if ("lastModifiedByName".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, sysUser.getUserName());
                        field.setAccessible(false);
                    }
                    if ("updateTime".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
    }

    /**
     * 获取类的所有属性，包括父类
     *
     * @param object 传入对象
     * @return 所有自定义字段
     */
    private Field[] getAllFields(Object object) {
        Class<?> clazz = object.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

}